import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Card, Icon, Avatar } from 'antd';
import { formatMoment } from '../../utils/utils';
import defaultCover from '../../assets/default.png';
import defaultAvatar from '../../assets/avatar.png';
import styles from './Card.less';

const { Meta } = Card;

@connect()
export default class extends PureComponent {
  state = {
    img: '',
    avatar: '',
  };

  componentDidMount() {
    const { picInfo } = this.props;

    this.setState({
      img: picInfo.imgUrl,
      avatar: picInfo.avatar,
    });
  }

  handleDetail = id => {
    const { onDetail } = this.props;
    onDetail(id);
  };

  handleRemove = id => {
    const { dispatch, onSuccess } = this.props;
    dispatch({
      type: 'picture/removeFromFavlist',
      payload: {
        params: {
          id,
        },
        onSuccess: () => {
          onSuccess();
        },
      },
    });
  };

  handleUserIndex = uid => {
    const { onUserIndex } = this.props;
    onUserIndex(uid);
  };

  render() {
    const { picInfo } = this.props;
    const { img, avatar } = this.state;

    return (
      <Card
        className={styles.imgWrapper}
        cover={
          <img
            src={img}
            onError={() => this.setState({ img: defaultCover })}
            onClick={() => this.handleDetail(picInfo.id)}
            alt="cover"
          />
        }
      >
        <Meta
          avatar={
            <Avatar
              size="large"
              src={avatar}
              onError={() => this.setState({ avatar: defaultAvatar })}
              onClick={() => this.handleUserIndex(picInfo.uid)}
            />
          }
          title={picInfo.brife}
          description={formatMoment(moment(picInfo.updated_at), 'type4')}
        />
        <div className={styles.btnWrapper}>
          <Icon type="delete" onClick={() => this.handleRemove(picInfo.id)} />
        </div>
      </Card>
    );
  }
}
